<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>AngularJS&middot;Hello AngularJS</title>
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.css">
    <style>
        .demo{
            margin-bottom:10px;
        }
    </style>
</head>
<body>

 <div class="container">
     <div class="row">
         <nav class="navbar navbar-default navbar-static-top">
             <div class="container-fluid">
                 <div class="navbar-header">
                     <a class="navbar-brand" href="../index.html">首页</a>
                 </div>
                 <ul class="nav navbar-nav">
                    <li class="active"><a href="javascript:void(0)">Link</a></li>
                    <li><a href="javascript:void(0)">Link2</a></li>
                 </ul>
             </div>
         </nav>
     </div>
     <div class="row demo" ng-app="MyAPP">
         <h3>AngularJS IOC依赖注入示例</h3>
         <div ng-controller="MyController">
             <button ng-click="hello()">Hello</button>
         </div>
     </div>
 </div>
 </div>
</body>
</html>
<script src="http://cdn.bootcss.com/angular.js/1.3.8/angular.js" type="text/javascript"></script>
<script>
    var app=angular.module("MyAPP",[]);

    //工厂是用于返回函数的值。它根据需求创造值，每当一个服务或控制器需要。它通常使用一个工厂函数来计算并返回对应值
    app.factory('Person', function($window) {
        var Person = {};
        Person.name="匿名用户";
        Person.sayHello = function() {
            $window.alert(this.name+":say hello");
        };
        return Person;
    });

    //服务是一个单一的JavaScript包含了一组函数对象来执行某些任务。服务使用service()函数，然后注入到控制器的定义。
    app.service('MyService', function(Person){
        this.saySomeThing = function() {
            return Person.sayHello();
        }
    });

    app.controller('MyController', function($scope, MyService) {
        $scope.hello = function() {
            MyService.saySomeThing();
        }
    });
</script>
